package com.example.mvc.controller;


import com.example.mvc.bean.User;
import com.example.mvc.service.UserService;
import com.example.mvc.util.Utils;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import javax.rmi.CORBA.Util;
import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      this.doPost(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 获取用户名和密码数据

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String email = request.getParameter("email");
        String phone = request.getParameter("phone");
        //默认设置最大借阅数和借阅天数
        int lend_num = 30;
        int max_num = 5;

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setName(name);
        user.setEmail(email);
        user.setPhone(phone);
        user.setLend_num(lend_num);
        user.setMax_num(max_num);
        if (Utils.isEmpty(username)||Utils.isEmpty(password)){
            request.setAttribute("register_msg","用户名和密码不能为空");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
            return;
        }

        //2. 调用service 注册
        boolean flag = service.register(user);
        //3. 判断注册成功与否
        if(flag){
            //注册功能，跳转登陆页面
            request.setAttribute("register_msg","注册成功，请登录");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }else {
            //注册失败，跳转到注册页面
            request.setAttribute("register_msg",username+"用户名已存在");
            request.getRequestDispatcher("/register.jsp").forward(request,response);
        }

    }
}